//
//  OAuthViewController.swift
//  自己的微博
//
//  Created by 张leslie45 on 16/1/13.
//  Copyright © 2016年 张leslie45. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController{

    //属性的webView
    let webView = UIWebView()
    
    //MARK:关闭页面
    @objc private func close(){
    
    //dismiss页面
       dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充账号
    @objc private func defaultAccount(){
       let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'oyonomg' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    }
    
    override func loadView() {
        //将根视图替换为webView
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

      //一旦设置颜色,全局有效
//     UINavigationBar.appearance().tintColor  = UIColor.orangeColor()
        
        //设置导航条
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    }

    
    //设置导航条
    private func setNavBar(){
       self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
    }
    //MARK:加载授权页面
    private func loadOAuthPage(){
        //1.获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        //2.可选的url
        let url = NSURL(string: urlString)!
        //3.获取request
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
   
    }
    
}
    
//swift 中 这样写,是将一类的协议方法写在一起更加好阅读 和 维护
//同一类的协议方法,就被放在理个扩展中
extension OAuthViewController:UIWebViewDelegate{
    
    //显示用户等待指示器
    func webViewDidStartLoad(webView: UIWebView) {
        //显示
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    //非常重要的协议方法
    //通常协议方法返回值为bool类型 返回yes通常控件可以正常运行
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //截取url中code授权码
      guard  let urlString = request.URL?.absoluteString else{
        
            //无法获取url的字符串,就直接不加载网页
           return false
        }
        
        if urlString.containsString("code=") {
            print(urlString)
            //将url中的参数获取到
            guard let query = request.URL?.query else {
                return false
            }
        
            let codeStr = "code="
            //将query转换成NSString subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code,query)
            //调用获取token的方法
            loadAccessToken(code)
            
            //不希望页面跳转到回调页面
            return false
        }
   
        return true
    }
    
    private  func  loadAccessToken(code:String){
       //请求token 和用户信息
        UserAccountViewModel().loadAccessToken(code){ (isSuccess) -> () in
            if !isSuccess{
            
              print("用户登录失败")
               //HUD提示用户登录失败
              SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
        //一定登录成功
            SVProgressHUD.showErrorWithStatus("登录成功")
            //执行dismiss操作的时候,HomeTableView没有真正释放掉
            //执行dismiss操作,对应的页面不会正在销毁
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //通知是同步的还是异步的
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwiftRootVC, object: "Welcome")
                print("come here")
            })
            
        
        }
    }
  
}

    
    
    
    
    
    
    
    



